<?php
namespace App\Libs\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Libs\Vendor\AliPaySdk\aop\AopClient;
use App\Libs\Vendor\AliPaySdk\aop\request\AlipayOpenAppQrcodeCreateRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantOrderConfirmRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantOrderCreditQueryRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantOrderCreditPayRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\AlipaySystemOauthTokenRequest;









/**
 * 小程序
 */
class ZhimaController extends Controller
{	
		private $aop=null;

		public function __construct()
		{   
			header("Content-type: text/html; charset=utf-8");
			if (is_null($this->aop))
			{
				$this->aop= new AopClient();
			}
			$this->aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		}
		
		public function setAppId($order_id,$channel=null)
		{	
			if (is_null($channel)) 
			{
				$order_comefrom=DB::table('orders')->where("order_id",$order_id)->value("order_comefrom");
				$app_id=DB::table('channel')->where("cha_name",$order_comefrom)->value("app_id");
			}else{
				$app_id=DB::table('channel')->where("cha_name",$channel)->value("app_id");
			}

			if (!empty($app_id)) $this->aop->appId=$app_id;
		}

		/**
		 * 生成小程序二维码
		 */
		public function alipayOpenAppQrcodeCreate()
		{
			$request = new AlipayOpenAppQrcodeCreateRequest ();

			$request->setBizContent("{" .
			"\"url_param\":\"page/rent/goodsdetail/goodsdetail\"," .
			"\"query_param\":\"goods_id=1\"," .
			"\"describe\":\"二维码描述\"" .
			"  }");
			$result = $this->aop->execute ($request); 
			 
			print_r($result);

			// $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
			// $resultCode = $result->$responseNode->code;
			// if(!empty($resultCode)&&$resultCode == 10000){
			//  echo "成功";
			// } else {
			//  echo "失败";
			// } 
		}


		/*
	     *  查询订单信息
	     *  @param order_no     芝麻订单号
	     *  @param outOrderNo   商户订单号(绿悦订单表订单号)
		*/
		public function confirm($order_no,$outOrderNo,$jump='kong')
		{	
			$this->setAppId($outOrderNo);
			$request = new  ZhimaMerchantOrderConfirmRequest ();
			$request->setBizContent("{" .
			"\"order_no\":\"".$order_no."\"," .
			"\"transaction_id\":\"".$outOrderNo."\"" .
			"  }");
			
			$result = $this->aop->execute ($request); 
            if($jump=='yanzheng'){
                var_dump($request);
            }
			if($result['zhima_merchant_order_confirm_response']['code'] == 10000)
			{	
				return $result['zhima_merchant_order_confirm_response'];
			}else{
				return false;
			}
		}
	

		public function test($oder_id='',$zm_order_no='',$yan='kong')
		{
            $a = '没有执行任何操作';
            if($yan=='quxiao'){
                $a=$this->base_credit_pay('CANCEL',$oder_id,$zm_order_no);
            }elseif($yan=='chaxun'){
                $a=$this->rent_query($oder_id,$zm_order_no);
            }
			var_dump($a);

		}
    //查询操作 芝麻信用为商户提供的订单信息查询能力
    private function rent_query($outOrderNo='',$order_no='')
    {
        $this->setAppId($outOrderNo);
        $request = new ZhimaMerchantOrderCreditQueryRequest ();

        $request->setBizContent("{" .
            "\"out_order_no\":\"".$outOrderNo."\"," .
            "\"zm_order_no\":\"".$order_no."\"" .
            "  }");

        $result = $this->aop->execute ($request);
        return $result;
    }

		/**
		*  信用订单支付接口 
		*  订单创建之后，随着业务的进展，商户可以调用该接口去推进订单的状态，例如取消订单、订单扣款完结以 及 分 期 付 款 ；
		*   蚂 蚁 开 放 平 台 接 口 文 档 地 址 为 ： https://docs.alipay.com/pr
		*   @param  order_operate_type   订单类型：订单取消(CANCEL) 订单完结(FINISH)  分期扣款(INSTALLMENT)
		*   @param  out_order_no         商户订单号(绿悦订单号)
		*   @param  zm_order_no          芝麻订单号
		*   @param  outtransn            资金单号(分期表ID)
		*   @param  pay_amount           金额完结时如果订单为0则默认不需要支付
		*/
		public function credit_pay($order_operate_type,$out_order_no,$zm_order_no,$out_trans_no='',$pay_amount=0,$remark='')
		{
            $result = $this->base_credit_pay($order_operate_type,$out_order_no,$zm_order_no,$out_trans_no,$pay_amount,$remark);
			 if ($result['zhima_merchant_order_credit_pay_response']['code'] == '10000') 
			 {
			 	return $result['zhima_merchant_order_credit_pay_response'];
			 }else{
			 	return  false;
			 }
		}
        //基本操作
        private function base_credit_pay($order_operate_type,$out_order_no,$zm_order_no,$out_trans_no='',$pay_amount=0,$remark='')
        {
            $request = new ZhimaMerchantOrderCreditPayRequest();

            if (!in_array($order_operate_type, array('CANCEL','FINISH','INSTALLMENT'))) exit('订单类型不正确');
            if (!$out_order_no) exit('商户订单号不存在');
            if (!$zm_order_no) exit('芝麻订单号不存在');

            $this->setAppId($out_order_no);

            if (empty($out_trans_no) && $order_operate_type!='INSTALLMENT' ) $out_trans_no=payJDSn();

            if (!$out_trans_no) exit('资金订单号不能为空');

            $request->setBizContent("{" .
                "\"order_operate_type\":\"".$order_operate_type."\"," .
                "\"out_order_no\":\"".$out_order_no."\"," .
                "\"zm_order_no\":\"".$zm_order_no."\"," .
                "\"out_trans_no\":\"".$out_trans_no."\"," .
                "\"pay_amount\":".$pay_amount."," .
                "\"remark\":\"".$remark."\"" .
                "  }");

            return $result = $this->aop->execute ($request);
        }

		/**
		 * 服务端获取access_token
		 */
		public function systemOauthToken($authCode,$device)
		{
			header("Content-type:text/html;charset=utf-8");

			$this->setAppId('',$device);

			$this->aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';

			$request = new AlipaySystemOauthTokenRequest ();
			
			$request->setGrantType("authorization_code");
			
			$request->setCode($authCode);

			$result = $this->aop->execute ($request); 

			if($result['alipay_system_oauth_token_response']['user_id'])
			{	
				return $result['alipay_system_oauth_token_response'];
			}else{
				return false;
			}
		}
  		
}